package com.shandiangou.crm.controller;

import com.shandiangou.crm.model.HongbaoLog;
import com.shandiangou.crm.model.vo.HongbaoQueryVo;
import com.shandiangou.crm.model.vo.HongbaoVo;
import com.shandiangou.crm.service.MarketService;
import com.shandiangou.crm.util.VoValidatorUtil;
import com.shandiangou.crm.web.HttpResult;
import com.shandiangou.market.open.HongbaoEntry;
import com.shandiangou.market.open.api.HongbaoGenerateService;
import com.shandiangou.market.open.api.HongbaoReadService;
import com.shandiangou.market.open.hongbao.HongbaoCreate;
import com.shandiangou.member.domain.UserDO;
import com.shandiangou.member.service.UserService;
import com.shandiangou.member.session.SdgSessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by jacky on 15/12/14.
 * 营销业务的Controllerc层
 */

@Controller
@RequestMapping("/crm/market")
public class MarketController {
    private static final Logger logger = LoggerFactory.getLogger(MarketController.class);

    @Autowired
    private UserService userService;//用户中心服务

    @Autowired
    private MarketService marketService;//营销操作业务类

    @Autowired
    private HongbaoGenerateService hongbaoGenerateService;//红包操作服务

    @Autowired
    private HongbaoReadService hongbaoReadService;//红包查询服务

    private static final String PLATFORM_SOURCE = "CRM";//红包渠道标识

    //private static final int MAX_TIMES = 15;//每日最多可以发送红包数
    private static final int MAX_TIMES = 100;//每日最多可以发送红包数

    /*
    private static Map<String, String> USER_MAP = new HashMap<String, String>();//红包白名单

    static {
        USER_MAP.put("15168390802", "15168390802");
        USER_MAP.put("15167161283", "15167161283");
        USER_MAP.put("15858259648", "15858259648");
        USER_MAP.put("13666635511", "13666635511");
        USER_MAP.put("18705595498", "18705595498");
        USER_MAP.put("15158872479", "15158872479");
        USER_MAP.put("15068887085", "15068887085");
        USER_MAP.put("18667042029", "18667042029");
        USER_MAP.put("15167116100", "15167116100");
        USER_MAP.put("13616546923", "13616546923");
        USER_MAP.put("13825235641", "13825235641");
        USER_MAP.put("15715703769", "15715703769");
        USER_MAP.put("13588813140", "13588813140");
    }
    */

    /**
     * 获取用户信息
     *
     * @return
     */
    private UserDO getUser() {
        if (SdgSessionUtil.getUserMobile() != null) {
            String mobile = SdgSessionUtil.getUserMobile().toString();
            return userService.getUserByMobile(mobile);
        } else {
            return null;
        }
    }

    /**
     * 发送红包
     *
     * @return
     */
    @RequestMapping(value = "/sendHongbao", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult sendHongbao(@RequestBody HongbaoVo hongbaoVo) {
        try {
            UserDO oUserDO = getUser();
            if (oUserDO != null) {
                String validateStr = VoValidatorUtil.validateVo(hongbaoVo);

                // 权限验证通过权限系统验证, 此处功能废弃
                //if (oUserDO != null && (oUserDO.getLevel() >= 1000 || USER_MAP.containsKey(oUserDO.getMobile().toString()))) {//1000权限和客服部才可以操作
                    if (validateStr != null) {
                        return HttpResult.Failure(-9, validateStr);
                    }

                    int count = marketService.countHongbaoByUserToday(oUserDO.getUserId());
                    if (count >= MAX_TIMES) {
                        return HttpResult.Failure(-10, "您今天发送的红包已经达到上限不能发了！");
                    }

                    UserDO hongbaoUserDO = userService.getUserByMobile(hongbaoVo.getMobile());//根据手机号码获得用户对象
                    if (hongbaoUserDO == null) {//用户不存在需要新建个用户\
                        UserDO newUserDO = new UserDO();
                        newUserDO.setMobile(Long.valueOf(hongbaoVo.getMobile()));
                        userService.insertUser(newUserDO);
                        hongbaoUserDO = userService.getUserByMobile(hongbaoVo.getMobile());//根据手机号码获得用户对象
                    }

                    HongbaoCreate create = new HongbaoCreate();

                    BeanUtils.copyProperties(hongbaoVo, create);
                    create.setUserId(hongbaoUserDO.getUserId());

                    HongbaoEntry oHongbaoEntry = hongbaoGenerateService.generateHongbao(oUserDO.getUserId(), PLATFORM_SOURCE, create);
                    HongbaoLog oHongbaoLog = new HongbaoLog();

                    BeanUtils.copyProperties(hongbaoVo, oHongbaoLog);
                    oHongbaoLog.setUserId(hongbaoUserDO.getUserId());
                    oHongbaoLog.setHongbaoId(oHongbaoEntry.getId());
                    oHongbaoLog.setOperator(oUserDO.getRealName());
                    oHongbaoLog.setOperatorId(oUserDO.getUserId());
                    marketService.insert(oHongbaoLog);

                    return HttpResult.Success("红包发送成功");
                /*
                } else {
                    return HttpResult.Failure(-98, "权限不足！");
                }
                */
            } else {
                return HttpResult.Failure(-98, "权限不足！");
            }
        } catch (Exception e) {
            logger.error("sendHongbao", e);
            return HttpResult.Failure(-99, "操作异常！");
        }
    }

    /**
     * 红包查询
     *
     * @param hongbaoQueryVo
     * @return
     */
    @RequestMapping(value = "/queryHongbaoByUserId", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult queryHongbaoByUserId(@RequestBody HongbaoQueryVo hongbaoQueryVo) {
        try {
            UserDO oUserDO = getUser();
            if (oUserDO != null) {
                String validateStr = VoValidatorUtil.validateVo(hongbaoQueryVo);
                if (oUserDO != null && (oUserDO.getLevel() >= 700)) {//700权限才可以操作
                    if (validateStr != null) {
                        return HttpResult.Failure(-9, validateStr);
                    }
                    if(hongbaoQueryVo.getUserId() != null){
                        return HttpResult.Success(hongbaoReadService.queryHongbaoByUserId(hongbaoQueryVo.getUserId(),hongbaoQueryVo.getUserStatus(),hongbaoQueryVo.getPage(),hongbaoQueryVo.getPageSize()));
                    }
                    UserDO user = userService.getUserByMobile(String.valueOf(hongbaoQueryVo.getMobile()));
                    if(user == null){
                        return HttpResult.Failure(-8, "用户不存在！");
                    }
                    return HttpResult.Success(hongbaoReadService.queryHongbaoByUserId(user.getUserId(),hongbaoQueryVo.getUserStatus(),hongbaoQueryVo.getPage(),hongbaoQueryVo.getPageSize()));
                } else {
                    return HttpResult.Failure(-98, "权限不足！");
                }
            } else {
                return HttpResult.Failure(-98, "权限不足！");
            }
        } catch (Exception e) {
            logger.error("queryHongbaoByUserId", e);
            return HttpResult.Failure(-99, "操作异常！");
        }
    }

    /**
     * 红包查询
     *
     * @param hongbaoQueryVo
     * @return
     */
    @RequestMapping(value = "/queryCardCouponByUserId", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult queryCardCouponByUserId(@RequestBody HongbaoQueryVo hongbaoQueryVo) {
        try {
            UserDO oUserDO = getUser();
            if (oUserDO != null) {
                String validateStr = VoValidatorUtil.validateVo(hongbaoQueryVo);
                if (oUserDO != null && (oUserDO.getLevel() >= 700)) {//700权限才可以操作
                    if (validateStr != null) {
                        return HttpResult.Failure(-9, validateStr);
                    }
                    if(hongbaoQueryVo.getUserId() != null){
                        return HttpResult.Success(hongbaoReadService.queryCardCouponByUserId(hongbaoQueryVo.getUserId(),hongbaoQueryVo.getUserStatus(),hongbaoQueryVo.getPage(),hongbaoQueryVo.getPageSize()));
                    }
                    UserDO user = userService.getUserByMobile(String.valueOf(hongbaoQueryVo.getMobile()));
                    if(user == null){
                        return HttpResult.Failure(-8, "用户不存在！");
                    }
                    return HttpResult.Success(hongbaoReadService.queryCardCouponByUserId(user.getUserId(),hongbaoQueryVo.getUserStatus(),hongbaoQueryVo.getPage(),hongbaoQueryVo.getPageSize()));
                } else {
                    return HttpResult.Failure(-98, "权限不足！");
                }
            } else {
                return HttpResult.Failure(-98, "权限不足！");
            }
        } catch (Exception e) {
            logger.error("queryHongbaoByUserId", e);
            return HttpResult.Failure(-99, "操作异常！");
        }
    }
}
